package com.hlc.helloWord.common.md5;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.security.MessageDigest;

/**
 * Created by helinchong on 2017/12/22.
 */
public class MD5Util {

    private static Logger logger = Logger.getLogger(MD5Util.class);

    public static String md5(String str){
        if(StringUtils.isEmpty(str)){
            throw new RuntimeException("加密字符isNull");
        }

        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");

            byte[] byteArray = str.getBytes("UTF-8");
            byte[] md5Bytes = md5.digest(byteArray);
            StringBuffer hexValue = new StringBuffer();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString();
        }catch (Exception e){
            logger.error(e.getMessage());
            return "";
        }
    }
}
